import { CENTEREVENTS, EventsRes, KEYBOARD_KEY } from '@amcax/base';
import { Picker3D, PickerMgr } from '@amcax/renderer';
import { nextmeshEventCenter } from '@app-nextmesh/common/events/EventCenter';
import { documentV2 } from '@app-nextmesh/domain';
import { NMTopoBaseCommand } from '@app-nextmesh/types/command';
import { useEffect } from 'react';
import { TopoDialogProps } from '../type';
const options = {
  line: true,
  point: true,
  face: true,
};
// 几何清理：释放
function GeometryReleaseEntity({ onClose }: TopoDialogProps) {
  const picker = PickerMgr.getPicker<Picker3D>('3d');
  useEffect(() => {
    nextmeshEventCenter()
      .setState('cmdTopoRelease')
      .on(CENTEREVENTS.POINTERMOVE, onPointMove)
      .on(CENTEREVENTS.POINTERUP, onPointUp)
      .on(CENTEREVENTS.KEYUP, onKeyUp);
    return () => {
      nextmeshEventCenter()
        .off(CENTEREVENTS.POINTERUP, onPointUp)
        .off(CENTEREVENTS.POINTERDOWN, onPointMove)
        .off(CENTEREVENTS.KEYUP, onKeyUp)
        .setDefault();
    };
  }, []);
  function onPointMove(e: EventsRes) {
    picker.pick(e, options);
  }
  // 筛选对应的点，线，面 的id
  async function onPointUp(e: EventsRes) {
    // 目前只做单选
    const info = picker.pick(e, options);
    const entityIds: string[] = [];
    if (info) {
      entityIds.push(info.meshId || info.edgeId || info.vertexId);
      await documentV2.releaseEntity(entityIds);
    }
  }
  function onKeyUp(e: EventsRes<KeyboardEvent>) {
    if (e.key === KEYBOARD_KEY.ESC) {
      onClose();
    }
  }
  return <></>;
}

export const cmdTopoRelease: NMTopoBaseCommand = {
  id: 'CmdTopoRelease',
  label: 'command.topo.release',
  icon: 'commands/curved/point',
  create: (label: string, onClose: () => void) => (
    <GeometryReleaseEntity
      title={''}
      onClose={onClose}
    />
  ),
};
